const state = {
  cart: JSON.parse(localStorage.goodsinfo || '[]'),
  userlist: JSON.parse(localStorage.userlist || '[]')
}

const mutations = {
  'ADD_CART'(state, value) {
    let flag = false
    state.cart.forEach((item) => {
      if (item.userid === value.userid) {
        if (item.id === value.id && item.userid === value.userid) {
          item.count += value.count
          flag = true
        }
      }
    })
    if (!flag) {
      state.cart.push(value)
    }
    localStorage.goodsinfo = JSON.stringify(state.cart)
  },
  newscount(state, { payload }) {
    state.cart.forEach(item => {
      if (item.id === payload.id) {
        item.count = payload.value
      }
    })
    localStorage.goodsinfo = JSON.stringify(state.cart)
  },
  setstatusone(state) {
    state.cart.forEach(item => {
      if (item.checked) {
        item.status = 1
        item.ctime = new Date().getTime()
      }
    })
    localStorage.goodsinfo = JSON.stringify(state.cart)
  },
  setstatusthree(state) {
    state.cart.forEach(item => {
      if (item.checked) {
        item.status = 3
        item.ctime = new Date().getTime()
      }
    })
    console.log(333)
    localStorage.goodsinfo = JSON.stringify(state.cart)
  },

  // 全选和反选
  'SELECE_ALL_CHECKOUT'(state, payload) {
    state.cart.forEach(item => {
      item.checked = payload
    })
  }
}

const actions = {}

const getters = {
  getAllCount(state) {
    let c = 0
    state.cart.forEach(item => {
      if (item.userid === state.userlist.userid) {
        c += item.count
      }
    })
    return c
  },
  allchecked(state) {
    // const flag = state.cart.every(item => {
    //   return item.checked
    // })
    // return flag

    return state.cart.every(item => item.checked)
  },
  total(state) {
    let sum = 0
    state.cart.forEach(item => {
      if (item.checked) {
        sum += item.price * item.count
      }
    })
    return sum
  },
  allnum(state) {
    let num = 0
    state.cart.forEach(item => {
      if (item.checked) {
        num += item.count
      }
    })
    return num
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
